import { defineTool, exec, run } from "@/utils.js"
import { existsSync, readFileSync } from "node:fs"

const commitMessageFile = ".commit.md"

async function hasStagedChanges(): Promise<boolean> {
  return (await run("git diff --cached --quiet")) !== 0
}

export async function commit(): Promise<string> {
  // 1. 检查提交信息文件是否存在
  if (!existsSync(commitMessageFile)) {
    return "未找到提交信息文件，跳过提交"
  }

  // 2. 读取文件内容
  let message: string
  try {
    message = readFileSync(commitMessageFile, "utf8").trim()
  } catch (err) {
    return `读取提交信息文件失败: ${err}`
  }

  if (!message) {
    return "提交信息为空，跳过提交"
  }

  // 3. 检查是否有暂存区更改
  const staged = await hasStagedChanges()

  // 4. 执行提交
  const cmd = staged
    ? `git commit -m ${JSON.stringify(message)}`
    : `git commit -a -m ${JSON.stringify(message)}`

  try {
    const output = (await exec(cmd)).toString("utf8").trim()
    return `提交成功: ${output}`
  } catch (err) {
    return `提交失败: ${err}`
  }
}

export default defineTool({
  name: "git_commit",
  description: "使用之前输出的提交信息文件进行提交",
  async callback(_extra) {
    return { content: [{ type: "text", text: await commit() }] }
  },
})
